﻿using Curry.Forum.Command.Handler.AutoFac;
using Curry.Forum.Command.Handler.AutoMapper;
using Curry.Forum.Command.Handler.CommandHandler;
using Curry.Forum.Infrastructure;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Curry.Forum.CommandService
{
    class Program
    {
        public static string ForumConnectionString = ConfigurationManager.ConnectionStrings["forum"].ConnectionString;


        //TODO:
        private static readonly ConnectionFactory rabbitMqFactory = new ConnectionFactory()
        {
            HostName = "localhost",
            UserName = "guest",
            Password = "guest",
            Port = 5672
        };


        const string TopExchangeName = "topic.test.exchange";
        const string TopQueueName = "topic.test.queue";

        static void Main(string[] args)
        {
            AutoMapperConfig.Configure();
            AutofacExt.RegisterApplication();

            ConfigSettings.ForumConnectionString = ForumConnectionString;

            ReadRedisInRedis();

            Console.WriteLine("按任意值，退出程序");
            Console.ReadKey();
        }

        public static void ReadRedisInRedis()
        {
            using (var connection = rabbitMqFactory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(TopQueueName, false, false, false, null);

                    var consumer = new EventingBasicConsumer(channel);
                    channel.BasicConsume(TopQueueName, false, consumer);
                    consumer.Received += (model, ea) =>
                    {
                        var body = ea.Body;
                        var message = Encoding.UTF8.GetString(body);

                        Console.WriteLine(message);

                        AutofacExt.GetFromFac<ArticleHandler>().CreateArticleModel(message);

                        channel.BasicAck(ea.DeliveryTag, false);
                    };
                    Console.ReadLine();
                }
            }
        }

    }
}
